import LoginSuccessAnimation from "@/components/LoginSuccessAnimationed";
import { router } from "expo-router";
import { useState } from "react";
import { KeyboardAvoidingView, StyleSheet, View } from "react-native";
import { Button, Text, TextInput } from "react-native-paper";
import { useAuth } from "./context/AuthContext";

export default function AuthScreen() {
  const { login } = useAuth();
  const [isSignUp, setIsSignUp] = useState<boolean>(false);
  const [userName, setUserName] = useState<string>("");
  const [password, setPassword] = useState<string>("");
  const [showAnimation, setShowAnimation] = useState(false)

  const handleLogin = async () => {
    await login(userName, password);
    setShowAnimation(true)
  };

  const handleAnimationFinished = () => {
    router.replace("/"); // 登录后跳转首页index
  }

  return (
    <KeyboardAvoidingView style={styles.container}>
      {
        showAnimation && <LoginSuccessAnimation onFinish={handleAnimationFinished} />
      }
      <View>
        <Text style={styles.title} variant="headlineMedium">
          {""}
          {isSignUp ? "Create an account" : "Welcome back"}
        </Text>
        <TextInput
          label="Email"
          autoCapitalize="none"
          keyboardType="email-address"
          placeholder="123@example.com"
          mode="outlined"
          value={userName}
          style={styles.input}
          onChangeText={setUserName}
        />

        <TextInput
          label="Password"
          autoCapitalize="none"
          mode="outlined"
          value={password}
          style={styles.input}
          secureTextEntry
          onChangeText={setPassword}
        />

        <Button mode="contained" style={styles.button} onPress={handleLogin}>
          Login
        </Button>
      </View>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#f5f5f5",
  },
  content: {
    flex: 1,
    padding: 16,
    justifyContent: "center",
  },
  title: {
    textAlign: "center",
    marginBottom: 24,
  },
  input: {
    backgroundColor: "white",
    marginBottom: 16,
  },
  button: {
    marginTop: 8,
  },
  switchModeButton: {
    marginTop: 16,
  },
});